package com.jinzhi.jzapi.examination.task;

import com.jinzhi.common.config.Constant;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Component
public class AutomaticMarkingJob implements Job {

    @Autowired
    private ExaminationPaperService examinationPaperService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private ExaminationResultsService examinationResultsService;
    @Autowired
    private ExaminationQuestionsService examinationQuestionsService;
    @Autowired
    private ExaminationAnswerSheetService examinationAnswerSheetService;
    @Autowired
    private ExaminationBatchService examinationBatchService;

    @Value("${server.port}")
    private String port;

    @Override
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) {
        if(!port.equals("8877")){
            return;
        }
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        ThreadContext.bind(manager);
        log.info("---------------------开始拆解答案计算成绩---------------------");
        //获取考试批次
      Map map = new HashMap();
      map.put("type",0);
      map.put("days",2);
        try {


      List<ExaminationBatchDO> examinationBatchDOS = examinationBatchService.selListExamBatch(map);
      for(ExaminationBatchDO examinationBatchDO :examinationBatchDOS) {

                //根据考试批次id对应的认证批次id,查询对应的所有考生信息
                List<StuSignUpDO> stuSignUpDOS = stuSignUpService.findByKv("cbatch_id", examinationBatchDO.getId());
          log.info("开始阅卷批次"+examinationBatchDO.getName()+"考生人数"+stuSignUpDOS.size());
          examinationBatchDO.setPassMark(60);
          if (stuSignUpDOS != null && stuSignUpDOS.size() > 0) {
              int stuNum=0;
              for (StuSignUpDO stuSignUpDO : stuSignUpDOS) {

                  Integer result = 0;

                  ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", examinationBatchDO.getId(), "state", 1);
                  //如果一个考生出现两套答卷只取其中一份答卷
                  if(examinationPaperDO==null)return;
                  List<ExaminationAnswerSheetDO> examinationAnswerSheetDOs = examinationAnswerSheetService
                          .findByKv("stu_sign_id", stuSignUpDO.getId(), "epaper_id", examinationPaperDO.getId());
                  ExaminationAnswerSheetDO examinationAnswerSheetDO = null;
                  //查询到考生对应的答卷

                  if(examinationAnswerSheetDOs!=null && examinationAnswerSheetDOs.size()>0)
                      examinationAnswerSheetDO=examinationAnswerSheetDOs.get(0);
                  List<Long> idss = examinationQuestionsService.selIdList(examinationPaperDO.getId());
                  //试卷对应的试题，有试题才算分，没有直接0分处理；
                  if(idss != null && idss.size()>0){
                      if (examinationAnswerSheetDO != null) {
                          //有答卷才算分，没有直接返回0
                          result = results(examinationAnswerSheetDO.getAnswerList(),idss);//考试总分

                      }
                  }
                  ExaminationResultsDO examinationResultsDOss = examinationResultsService
                          .findOneByKv("cbatch_id", examinationBatchDO.getCbatchId(), "ebatch_id", examinationBatchDO.getId(), "stu_sign_id", stuSignUpDO.getId());
                  if (examinationResultsDOss == null) {
                      ExaminationResultsDO examinationResultsDO = new ExaminationResultsDO();
                      examinationResultsDO.setCbatchId(examinationBatchDO.getCbatchId());//认证批次id
                      examinationResultsDO.setEbatchId(examinationPaperDO.getEbatchId());//考试批次id
                      examinationResultsDO.setStuSignId(stuSignUpDO.getId());//考生信息id
                      if(examinationAnswerSheetDO == null){
                          examinationResultsDO.setState(1);//缺考
                      }else{
                          examinationResultsDO.setState(0);//正常
                      }
                      examinationResultsDO.setTotalScore(result.doubleValue());//考试成绩
                      boolean b = examinationResultsService.insert(examinationResultsDO);
                      if(b){
                          stuNum++;
                      }
//                    if (!b) {
//                        return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的成绩录入失败！");
//                    } else {
                      if (examinationAnswerSheetDO != null) {
                          examinationAnswerSheetDO.setState(1);//改成已阅卷
                          boolean c = examinationAnswerSheetService.updateById(examinationAnswerSheetDO);
//                            if (!c) {
//                                return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "答卷状态更改失败！");
//                            }
                      }

                      if (result >= examinationBatchDO.getPassMark()) {
                          stuSignUpDO.setState(6);//状态改为理论已过
                          boolean sbc = stuSignUpService.updateById(stuSignUpDO);
//                            if (!sbc) {
//                                return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的更新状态失败！");
//                            }
                      }


                      //  }
                  }else {
                      if(examinationAnswerSheetDO == null){
                          examinationResultsDOss.setState(1);//缺考
                      }else{
                          examinationResultsDOss.setState(0);//正常
                      }
                      if(  examinationResultsDOss.getTotalScore()<result.doubleValue()){
                          examinationResultsDOss.setTotalScore(result.doubleValue());//考试成绩
                          boolean b = examinationResultsService.updateById(examinationResultsDOss);
                      }



//                    if (!b) {
//                        return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的成绩录入失败！");
//                    } else {
                      if (examinationAnswerSheetDO != null) {
                          examinationAnswerSheetDO.setState(1);//改成已阅卷
                          boolean c = examinationAnswerSheetService.updateById(examinationAnswerSheetDO);
//                            if (!c) {
//                                return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "答卷状态更改失败！");
//                            }
//                        }

                          if (result >= examinationBatchDO.getPassMark()) {
                              stuSignUpDO.setState(6);//状态改为理论已过
                              boolean sbc = stuSignUpService.updateById(stuSignUpDO);
//                            if (!sbc) {
//                                return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的更新状态失败！");
//                            }
                          }

                      }
                  }

              }
              log.info("新增阅卷成功人数="+stuNum);
          }

      }
        }catch (Exception e){
            log.info("异常"+e.getMessage());
            e.printStackTrace();
        }
    }

    private Integer results(String answers,List<Long> idss) {
        Integer results = 0;
        if(StringUtils.isNotBlank(answers)){
            JSONArray jsonArray2 = JSONArray.fromObject(answers);
            for(int i = 0;i<jsonArray2.size();i++){
                if(idss.indexOf(Long.parseLong(jsonArray2.getJSONObject(i).getString("id"))) > -1){
                    ExaminationQuestionsDO examinationQuestionsDO = examinationQuestionsService.selectById(Long.parseLong(jsonArray2.getJSONObject(i).getString("id")));
                    if(!jsonArray2.getJSONObject(i).containsKey("value"))continue;
                    if (examinationQuestionsDO.getType() == 0 || examinationQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                        if (examinationQuestionsDO.getAnswers().equals(jsonArray2.getJSONObject(i).getString("value"))) {
                            //System.out.println("正确题目ID："+jsonArray2.getJSONObject(i).getString("id"));
                            results = results + examinationQuestionsDO.getScore();
                        }
                    } else if (examinationQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
//                        String[] ssb = jsonArray2.getJSONObject(i).getString("value").split(";;");
//                        String answer = "";
//                        for (int n = 0; n < ssb.length; n++) {
//                            if (answer == "") {
//                                answer = ssb[n];
//                            } else {
//                                answer = answer + ";;" + ssb[n];
//                            }
//                        }
                        String[] ssb = jsonArray2.getJSONObject(i).getString("value").split(";;");

                        //------
                        boolean isRight=true;
                        if(ssb.length>1){
                            if(ssb[1]==null||ssb[1]==""){
                                isRight=false;
                            }else{
                                String answer = examinationQuestionsDO.getAnswers();
                                if(ssb.length!=answer.split(";;").length){
                                    isRight=false;
                                }else {
                                    for (int n = 0; n < ssb.length; n++) {
                                        //if (ssb[n].equals("A") || ssb[n].equals("B") || ssb[n].equals("C") || ssb[n].equals("D") || ssb[n].equals("E") || ssb[n].equals("F")) {
                                        if (!answer.contains(ssb[n])) {
                                            isRight = false;
                                            break;
                                        }

                                    }
                                }
                            }
                        }else {
                            isRight=false;
                        }
                        if (isRight) {
                            results = results + examinationQuestionsDO.getScore();
                        }



                    }
                }
            }
        }

        return results;
    }
//    private Integer results(String answers,List<Long> idss) {
//        Integer results = 0;
//        if(StringUtils.isNotBlank(answers)){
//            JSONArray jsonArray2 = JSONArray.fromObject(answers);
//            for(int i = 0;i<jsonArray2.size();i++){
//                if(idss.indexOf(Long.parseLong(jsonArray2.getJSONObject(i).getString("id"))) > -1){
//                    ExaminationQuestionsDO examinationQuestionsDO = examinationQuestionsService.selectById(Long.parseLong(jsonArray2.getJSONObject(i).getString("id")));
//                    if(!jsonArray2.getJSONObject(i).containsKey("value"))continue;
//                    if (examinationQuestionsDO.getType() == 0 || examinationQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
//                        if (examinationQuestionsDO.getAnswers().equals(jsonArray2.getJSONObject(i).getString("value"))) {
//                            results = results + examinationQuestionsDO.getScore();
//                        }
//                    } else if (examinationQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
//                        String[] ssb = jsonArray2.getJSONObject(i).getString("value").split(";;");
//                        String answer = "";
//                        for (int n = 0; n < ssb.length; n++) {
//                            if (answer == "") {
//                                answer = ssb[n];
//                            } else {
//                                answer = answer + ";;" + ssb[n];
//                            }
//                        }
//
//                        if (examinationQuestionsDO.getAnswers().equals(answer)) {
//                            results = results + examinationQuestionsDO.getScore();
//                        }
//
//
//
//                    }
//                }
//            }
//        }
//
//        return results;
//
//    }

}
